package com.lzk.basic.util;

import com.lzk.basic.jwt.JwtUtils;
import com.lzk.basic.jwt.Payload;
import com.lzk.basic.jwt.RsaUtils;
import com.lzk.user.domain.LoginData;
import com.lzk.user.domain.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 从jwt token中解密获取loginData
 */
public class LogininfoContext {

    public static LoginInfo getLogininfo(HttpServletRequest request){
        try {
            String token = request.getHeader("token");

            if(token != null) {//不为空
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //将jwtToken解析成想要的数据：LoginData
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                if(payload != null) {//登录成功，并没有过期
                    //获取登录对象
                    LoginInfo logininfo = payload.getLoginData().getLoginInfo();
                    return logininfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }
}
